package com.feicheng.lanniao.controller.weChatNativePay.carSellInfo;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.feicheng.lanniao.controller.weChatNativePay.constant.WechatPayConfig;
import com.feicheng.lanniao.controller.weChatNativePay.pojo.CarRentalAndSellPcClientPOJO;
import com.feicheng.lanniao.util.HttpUtils;
import com.feicheng.lanniao.util.QRCodeUtil;
import com.feicheng.lanniao.util.SnowflakeIdWorker;
import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于车辆出售发布支付
 */
@RestController
@Log4j2
public class WeixinCarSellInfoNativeController {

    @GetMapping("/weixinpay/CarSellInfo")
    @ResponseBody
    public byte[] weixinpay(CarRentalAndSellPcClientPOJO carRentalAndSellPcClientPOJO) throws JsonProcessingException {
        log.info("WeixinCarSellInfoNativeController的weixinpay方法进入," +
                "参数carRentalAndSellPcClientPOJO为"+carRentalAndSellPcClientPOJO);
        //结合兰鸟业务,将发布信息转化为JSON
        String attach = JSONObject.toJSONString(carRentalAndSellPcClientPOJO);
        //封装请求参数
        Map<String,Object> map = new HashMap<>();
        map.put("appid", WechatPayConfig.APPID);
        map.put("attach", attach); //附加信息   这里可能会超过128位
        map.put("mchid", WechatPayConfig.MCH_ID);
        map.put("description","测试数据");
        map.put("out_trade_no",  new SnowflakeIdWorker(1, 1).nextId() + "");
        map.put("notify_url", WechatPayConfig.CAR_SELL_INFO_CALLBACK);  //回调接口只有一个...
        Map<String, Object> amount = new HashMap();
        amount.put("total", Integer.parseInt(getMoney("0.01")));
        amount.put("currency", "CNY");
        map.put("amount", amount);
        ObjectMapper objectMapper = new ObjectMapper();
        String body = objectMapper.writeValueAsString(map);
        Map<String, Object> stringObjectMap = HttpUtils.doPost(WechatPayConfig.GATEWAY, body);
        log.info("stringObjectMap"+stringObjectMap);
        String codeUrl = stringObjectMap.get("code_url").toString();
        //生成付款二维码
        //生成二维码配置
        Map<EncodeHintType, Object> hints = new HashMap<>();
        //设置纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        //编码类型
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        try {
            //生成微信支付二维码
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            String logopath = null;
            logopath = ResourceUtils.getFile(WechatPayConfig.LOGO).getAbsolutePath();
            BufferedImage buff = QRCodeUtil.encode(codeUrl, logopath, false);
            ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
            ImageIO.write(buff, "JPEG", imageOut);
            imageOut.close();
            ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
            return FileCopyUtils.copyToByteArray(input);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 元转换成分
     *
     * @param money
     * @return
     */
    private String getMoney(String money) {
        if (money == null || money.equalsIgnoreCase("0")) {
            return "";
        }
        // 金额转化为分为单位
        // 处理包含, ￥ 或者$的金额
        String currency = money.replaceAll("\\$|\\￥|\\,", "");
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong = 0l;
        if (index == -1) {
            amLong = Long.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
        } else if (length - index == 2) {
            amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
        } else {
            amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
        }
        return amLong.toString();
    }
}
